<script setup lang="ts">
  import { loginPasswordApi } from '@/apis/user'
  import { useUserStore } from '@/stores/user'
  import { ref } from 'vue'

  const isAgree = ref(false)
  const formData = ref({
    mobile: '13230000002',
    password: 'abc12345',
  })

  // 表单组件 ref
  const form = ref<UniHelper.UniFormsInstance>()
  // 表单校验规则
  const formRules: UniHelper.UniFormsRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请输入手机号' },
        { pattern: '^1[0-9]{10}$', errorMessage: '请输入正确的手机号' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入密码' },
        { pattern: '^[a-zA-Z0-9]{8,16}$', errorMessage: '请输入8到16位字母、数字组合' },
      ],
    },
  }

  // 提交表单
  const onSubmit = async () => {
    try {
      // 校验表单所有字段
      await form.value?.validate?.()
      if (!isAgree.value) {
        return uni.showToast({ title: '请勾选同意用户协议', icon: 'none' })
      }
      const res = await loginPasswordApi(formData.value)
      const store = useUserStore()
      store.setToken(res.token)
      store.userId = res.id
      uni.showToast({ title: '登录成功', icon: 'success' })
      uni.switchTab({ url: '/pages/index/index' })
    } catch (error) {
      console.log(error)
    }
  }
</script>
<template>
  <uni-forms class="login-form" ref="form" :rules="formRules" :model="formData">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
        v-model="formData.password"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit()">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
